#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <QDebug>
#include <QMessageBox>
#include <QDateTime>
#include <QDir>

using namespace cv;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , cap(0) // 打开默认摄像头
{
    ui->setupUi(this);
    cameraLabel = ui->cameraLabel;
    cameraLabel2 = ui->cameraLabel2;


    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateCameraFrame);
    timer->start(30); // 更新间隔30ms

    if (!cap.isOpened()) {
        qDebug() << "无法打开摄像头";
        QMessageBox::critical(this, "错误", "无法打开摄像头");
    }

}

MainWindow::~MainWindow()
{
    delete ui;
    cap.release();
    delete timer;
}

void MainWindow::updateCameraFrame()
{
    Mat frame;
    cap >> frame;
    if (frame.empty()) {
        qDebug() << "无法读取数据";
        QMessageBox::critical(this, "错误", "无法从摄像头读取数据");
        return;
    }
    QImage img = MatToQImage(frame);
    cameraLabel->setPixmap(QPixmap::fromImage(img));
}

QImage MainWindow::MatToQImage(const cv::Mat &mat)
{
    if (mat.type() == CV_8UC1) {
        QImage image(mat.cols, mat.rows, QImage::Format_Grayscale8);
        uchar *ptr = image.bits();
        for (int i = 0; i < mat.rows; ++i) {
            memcpy(ptr, mat.ptr(i), mat.cols);
            ptr += image.bytesPerLine();
        }
        return image;
    } else if (mat.type() == CV_8UC3) {
        const uchar *qImgBuf = (const uchar*)mat.data;
        QImage img(qImgBuf, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return img.rgbSwapped();
    } else {
        qDebug() << "cv::Mat image type not handled in switch:" << mat.type();
        return QImage();
    }
}



void MainWindow::on_pushButton_clicked()
{
    Mat frame;
    cap >> frame;
    if (frame.empty()) {
        qDebug() << "无法读取数据";
        QMessageBox::critical(this, "错误", "无法从摄像头读取数据");
        return;
    }
    QImage img = MatToQImage(frame);
    cameraLabel2->setPixmap(QPixmap::fromImage(img));
    QString savePath = "D:/image/";
    QDir dir(savePath);
    if (!dir.exists()) {
        dir.mkpath(savePath);
    }
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".jpg";
    QString filePath = savePath + fileName;

    bool isSaved = cv::imwrite(filePath.toStdString(), frame);

    if (isSaved) {
        QMessageBox::information(this, "图片保存", "图片已成功保存到：" + filePath);
    } else {
        QMessageBox::critical(this, "错误", "保存图片失败");
    }
}

